<?php
namespace app\admin\controller;
use think\Db;
use app\admin\model\Admin as AdminModel;
use app\admin\model\AdminLogin;

use app\admin\model\AuthRule as AuthRuleModel;
use app\admin\model\AuthGroup as AuthGroupModel;
use app\admin\model\AuthGroupAccess as AuthGroupAccessModel;

class Auth extends Base{

    /* 菜单列表/权限 */
    public function rule()
    {
        $db = new AuthRuleModel();
        $sort = input('post.sort/a');
        if(!empty($sort)){
            foreach($sort as $k=>$v){
                $v = intval($v);
                $db->where('id',$k)->setField('sort',$v);
            }
        }
        $list = $db->order('sort')->select();
        $list = category_merge($list,0,0,'id');
        $this->assign('list',$list);
        return $this->fetch();
    }
    public function rule_add(){
        $db = new AuthRuleModel();
        $list = $db->order('sort')->select();

        if(Request()->isPost()){
            $data = input('post.');
            if(empty($data['name'])){
                return ['status'=>'n','info'=>'规则不能为空'];
            }
            $id = $data['id'];
            unset($data['id']);
            if($id){
                $children = get_children($list,$id,'id');
                $children[] = $id;
                if(in_array($data['parent_id'], $children)){
                    $this->error('不能使用自己或下级作为为上级分类');die;
                }
                $b = $db->where('id',$id)->update($data);
            }else{
                $b = $db->save($data);
            }

            if( $b !== false ){
                return ['status'=>'y','info'=>'操作成功'];
            }else{
                return ['status'=>'n','info'=>'操作失败'];
            }
        }else{
            $id = input('id',0);
            if($id > 0){
                $row = $db->where('id',$id)->find();
            }else{
                $row['status'] = 1;
            }
            $list = category_merge($list,0,0,'id');
            return view('',['row'=>$row,'list'=>$list]);
        }
    }
    public function rule_del(){
        $id = trim(input('id'),',');
        $db = new AuthRuleModel();
        $b = AuthRuleModel::destroy($id);
        if($b){
            $list = $db->select();
            $ids = explode(',', $id);
            $children = [];
            foreach($ids as $v){
                $tmp = get_children($list,$v,'id');
                $children = array_merge($children,$tmp);
            }
            if($children){
                $where['id'] = ['in',$children];
                $db->where($where)->delete();
            }
            $count = $db->count();
            return ['status'=>'y','info'=>'删除成功^_^','children'=>$children,'count'=>$count];
        }else{
            return ['status'=>'n','info'=>'删除失败*_*'];
        }
    }

    /* 角色列表 */
    public function role()
    {
        $list = AuthGroupModel::order('id', 'desc')->select();
        foreach ($list as $k => $v) {
            $users = '';
            $uid = (new AuthGroupAccessModel)->where('group_id', $v['id'])->select()->toArray();
            $uid = array_column($uid, 'uid');
            if ($uid) {
                $admin = (new AdminModel)->where('id', 'in', $uid)->select()->toArray();
                $admin = array_column($admin, 'username');
                $users = implode(',', $admin);
            }
            $list[$k]['users'] = $users;
        }
        return view('',['list'=>$list]);
    }


    /* 角色添加/修改 */
    public function role_add(){
        $db = new AuthGroupModel();

        if(Request()->isPost()){
            $data = input('post.');
            if(empty($data['title'])){
                return json(['status'=>'n','info'=>'角色名称为空']);
            }
            $data['rules'] = !empty($data['rules']) ? implode(',',$data['rules']) : '';
            $id = $data['id'];unset($data['id']);
            if($id){
                $b = (new AuthGroupModel)->where('id',$id)->update($data);
            }else{
                if((new AuthGroupModel)->where('title',$data['title'])->find()){
                    return json(['status'=>'n','info'=>'角色名称不能重复']);
                }
                $b = (new AuthGroupModel)->save($data);
            }
            if($b !== false){
                return ['status'=>'y','info'=>'操作成功'];
            }else{
                return ['status'=>'n','info'=>'操作失败'];
            }
        }else{
            $id = input('id',0);
            if($id > 0){
                $row = $db->where('id',$id)->find();
                $row['rules'] = !empty($row['rules']) ? explode(',', $row['rules']) : [];
            }else{
                $row = ['status'=>1,'rules'=>[]];
            }
            $rule = (new AuthRuleModel)->field('id,title,parent_id')->where(['status'=>"1"])->order('sort')->select();
            $rule = rule_tree($rule);
            return view('',['row'=>$row,'rule'=>$rule]);
        }
    }
    public function role_del()
    {
        $id = trim(input('id'),',');
        $b = AuthGroupModel::destroy($id);
        if($b){
            return ['status'=>'y','info'=>'删除成功'];
        }else{
            return ['status'=>'n','info'=>'删除失败'];
        }
    }

    public function admin(){
        $list = AdminModel::order('id','desc');
        $data = input('param.');

        if (isset($data['start']) && $data['start'] && isset($data['end']) && $data['end']) {
            $data['start'] = $data['start'] . ' 00:00:00';
            $data['end'] = $data['end'] . ' 23:55:55';
            $list->where('updated', '>=', $data['start']);
            $list->where('updated', '<=', $data['end']);
        }
        if (isset($data['word']) && $data['word']) {
            $list->where('username', $data['word']);
        }
        $list = $list->paginate(10, false, ['query' => $this->request->param()]);

        foreach($list as $k=>$v){
            $role = '';
            $group_id = (new AuthGroupAccessModel)->where(['uid'=>$v['id']])->select()->toArray();
            $group_id = array_column($group_id,'group_id');
            if($group_id){
                $group = (new AuthGroupModel)->where('id','in',$group_id)->select()->toArray();
                $group = array_column($group,'title');
                $rule = implode(',', $group);
                $list[$k]['roles'] = $rule;
            }
        }

        return view('',['list'=>$list]);
    }

    public function admin_add(){
        $admin = new AdminModel();

        if(Request()->isPost()){
            $data = input('post.');
            $role = input('post.role/a');

            //验证
            $validate = new \app\admin\validate\Admin;
            if($data['id'] > 0){
                $vali = $validate->scene('edit')->check($data);
            }else{
                $vali = $validate->scene('add')->check($data);
            }
            if(!$vali){
                return ['status'=>'n','info'=>$validate->getError()];
            }

            unset($data['role']);
            if($data['id'] > 0 && empty($data['password'])){
                unset($data['password']);
            }
            if(!empty($data['password'])){
                $data['password'] = md5($data['password']);
            }
            
            if($data['id']){
                $b = $admin->save($data,['id'=>$data['id']]);
            }else{
                unset($data['id']);
                $b = $admin->save($data);
            }

            if($b !== false){
                if($role){
                    $admin->auth_group_access($role);
                }
                return ['status' => 'y', 'info' => '操作成功'];
            }else{
                return ['status' => 'n', 'info' => '操作失败'];
            }
        }else{
            $id = input('id',0);
            if($id > 0){
                $row = AdminModel::get($id);
                $roles = (new AuthGroupAccessModel)->where(['uid'=>$id])->select()->toArray();
                $row['roles'] = array_column($roles,'group_id');
            }else{
                $row['roles'] = [];
            }
            /* 角色列表 */
            $role = (new AuthGroupModel)->field('id,title')->where(['status'=>"1"])->select();
            $this->assign('role',$role??[]);
            $this->assign('row',$row);
            return $this->fetch();
        }
    }
    public function admin_del(){
        $id = trim(input('id'),',');
        $ids = explode(',', $id);
        if(in_array('5be3cfdcdf45930fcd3f9bf2',$ids)){
            return ['status'=>'n','info'=>'不允许删除超级管理员'];
        }
        $b = AdminModel::destroy(trim(input('id')),',');
        if($b){
            (new AuthGroupAccessModel)->where('uid','in',$id)->delete();
            return ['status'=>'y','info'=>'删除成功'];
        }else{
            return ['status'=>'n','info'=>'删除失败'];
        }
    }
    public function repeat(){
        $repeat = input('repeat');
        if(!empty($repeat)){
            $b = (new AdminModel)->where(['username'=>$repeat])->column('id');
            if($b){
                return ['status'=>'n','此账号已经被使用'];
            }
        }
    }
}